package com.xjzd.std.concurrency;

public class AlternatePrinting {
    private static final Object lock = new Object();
    private static int number = 1;
    private static boolean toggle = true;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while (number <= 100) {
                synchronized (lock) {
                    if (!toggle) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    if (number <= 100) {
                        System.out.println("Thread 1: " + number++);
                    }
                    toggle = !toggle;
                    lock.notifyAll();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while (number <= 100) {
                synchronized (lock) {
                    if (toggle) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    if (number <= 100) {
                        System.out.println("Thread 2: " + number++);
                    }
                    toggle = !toggle;
                    lock.notifyAll();
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}